package viqiang.ye.mallpuny.service.impl;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import viqiang.ye.mallpuny.common.api.CommonResult;
import viqiang.ye.mallpuny.common.utils.JwtTokenUtil;
import viqiang.ye.mallpuny.dao.UmsAdminRoleRelationDao;
import viqiang.ye.mallpuny.mbg.mapper.UmsAdminMapper;
import viqiang.ye.mallpuny.mbg.model.UmsAdmin;
import viqiang.ye.mallpuny.mbg.model.UmsAdminExample;
import viqiang.ye.mallpuny.mbg.model.UmsPermission;
import viqiang.ye.mallpuny.service.UmsAdminService;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class UmsAdminServiceImpl implements UmsAdminService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsAdminServiceImpl.class);
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UmsAdminMapper adminMapper;
    @Autowired
    private UmsAdminRoleRelationDao adminRoleRelationDao;

    @Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin>  umsAdminList = adminMapper.selectByExample(example);
//        Optional<List<UmsAdmin>> optionalUmsAdminList = Optional.ofNullable(umsAdminList);
        if (!CollectionUtils.isEmpty(umsAdminList)) {
            return umsAdminList.get(0);
        }
        return UmsAdmin.builder().build();
    }

    @Override
    public CommonResult<UmsAdmin> register(UmsAdmin umsAdminParam) {
        UmsAdmin umsAdmin = UmsAdmin.builder().build();
        BeanUtils.copyProperties(umsAdminParam, umsAdmin);
        umsAdmin.setCreateTime(new Date());
        umsAdmin.setStatus(1);
        //查询是否有相同用户名的用户
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(umsAdmin.getUsername());
        List<UmsAdmin> umsAdmins = adminMapper.selectByExample(example);
        if (umsAdmins != null && umsAdmins.size() > 0) {
            return CommonResult.failed("已存在同名用户，请修改.");
        }
        String encodePassword = passwordEncoder.encode(umsAdmin.getPassword());
        umsAdmin.setPassword(encodePassword);
        adminMapper.insert(umsAdmin);
        return CommonResult.success(umsAdmin, "注册用户成功.");
    }

    @Override
    public Map<String,String> login(String username, String password) {
        Map tokenMap = Maps.newHashMap();
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new BadCredentialsException("密码不正确.");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null,userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            String token = jwtTokenUtil.generateToken(userDetails);
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
        }catch (AuthenticationException ex) {
            LOGGER.warn("登录异常:{}", ex.getMessage());
        }
        return tokenMap;
    }

    @Override
    public List<UmsPermission> getPermissionList(Long adminId) {
        return adminRoleRelationDao.getPermissionList(adminId);
    }
}
